<?php

namespace app\admin\service;

use app\admin\item\GoodCategoryLoader;
use app\admin\pipeline\ItemAdapter;
use app\common\model\GoodCategoryModel as GoodCategoryModel;
use app\admin\validate\GoodCategoryValidate as GoodCategoryValidate;


class GoodCategoryService
{


    public static function getByID($id)
    {
        $adapter = new  ItemAdapter(GoodCategoryModel::class);
        return $adapter->id($id)->getModel();
    }

    public static function getAll()
    {
        return GoodCategoryModel::where([["status", "<>", "-1"]])->order(["pid" => "asc", "weight" => "desc", "id" => "desc"])->select()->toArray();
    }


    public static function getList($param)
    {
        $pagination = filter_pagination(@$param['page'], @$param['limit']);
        $data = [];
        $loader = new GoodCategoryLoader();
        $where = $loader->addWhere(['status', '<>', -1])->loadWhere();
        $query = GoodCategoryModel::field("id,weight,create_time,images,title,pid,status")->where($where)->order(["weight" => "desc", "create_time" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->append(['status_text'])->select()->toArray();
        }
        return $data;
    }

    public static function save($param)
    {
        $loader = new GoodCategoryLoader();
        $data = $loader->addVal($param)->addVerify(GoodCategoryValidate::class, GoodCategoryValidate::SCENE_SAVE)->loadItem();
        $adapter = new ItemAdapter(GoodCategoryModel::class);
        $res = $adapter->save($data);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }


    public static function del($params)
    {
        $adapter = new ItemAdapter(GoodCategoryModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']], ["id", "<>", 1]], ["status" => -1]);
    }


}